#include "create.h"
#include "qfile.h"
#include "qtextstream.h"
#include <QTcpSocket>
#include <util/usersquota.h>
#include <QTime>

static QString temppath="/home/lou/Openstack/temp";

Create::Create(QObject *parent) : QThread(parent)
{
    qRegisterMetaType<VM>("VM");
}

Create::~Create()
{
    qDebug() << " delete Create";
}

void Create::revPassage(QByteArray& passage,QTcpSocket* socket)
{
    m_pSocket=socket;
    m_passage=passage;
}
bool Create::parsePassage(QByteArray& passage,VM& vm)
{
    QList<QByteArray> list = passage.split(',');
    if(list.size()==8)
    {
        vm.userName=list.at(1);
        vm.password=list.at(2);
        vm.vmName=list.at(3);
        vm.vmImage=list.at(4);
        vm.vcpus=list.at(5);
        vm.ram=list.at(6);
        vm.disk=list.at(7);
        return true;
    }
    return false;
}
bool Create::createVm(VM& vm,QByteArray& result)
{
    UsersQuota usersQuota;
    if(!usersQuota.checkIdentity(vm.userName,vm.password))//检查用户身份
    {
        return false; //user hasn't register or password error
    }
    //创建启动虚拟机的脚本
    QString currentTime=QTime::currentTime().toString();
    QString shPath=temppath+'/'+vm.userName+currentTime+".sh"; //启动脚本路径
    QString resPath=temppath+"/"+vm.userName+currentTime+".txt";//启动结果文本路径
    QFile fout(shPath);
    if(!fout.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        return false;
    }
    QTextStream stream(&fout);
    Quota curQuota;
    int addCpu=vm.vcpus.toInt();
    int addRam=vm.ram.toInt();
    int addDisk=vm.disk.toInt();
    if(!usersQuota.addAndGetQuota(vm.userName,addCpu,addRam,addDisk,curQuota))//the function doesn't change file log
    {
        return false;
    }
    stream<<"#!/bin/sh\n";
    stream<<"export OS_PROJECT_DOMAIN_ID=default\n"
          <<"export OS_USER_DOMAIN_ID=default\n"
          <<"export OS_PROJECT_NAME=admin\n"
          <<"export OS_TENANT_NAME=admin\n"
          <<"export OS_USERNAME=admin\n"
          <<"export OS_PASSWORD=root\n"
          <<"export OS_AUTH_URL=http://controller:35357/v3\n"
          <<"export OS_IDENTITY_API_VERSION=3\n";
    stream<<"tenant=$(openstack project list | awk '/"<<vm.userName+"/ {print $2}')\n";
    stream<<"nova quota-update --instances "<<curQuota.vmNum<<" $tenant\n";
    stream<<"nova quota-update --cores "+curQuota.vcups+" $tenant\n";
    stream<<"nova quota-update --ram "+curQuota.ram+" $tenant\n";
    stream<<"openstack flavor delete m1.other\n";
    stream<<"openstack flavor create --id 0 --vcpus "<<vm.vcpus+" --ram "<<vm.ram<<" --disk "<<vm.disk<<" m1.other\n";
    stream<<"export OS_PROJECT_DOMAIN_ID=default\n"
          <<"export OS_USER_DOMAIN_ID=default\n"
          <<"export OS_PROJECT_NAME="<<vm.userName<<"\n"
          <<"export OS_TENANT_NAME="<<vm.userName<<"\n"
          <<"export OS_USERNAME="<<vm.userName<<"\n"
          <<"export OS_PASSWORD="<<vm.password<<"\n"
          <<"export OS_AUTH_URL=http://controller:5000/v3\n"
          <<"export OS_IDENTITY_API_VERSION=3\n";
    stream<<"nova boot --flavor m1.other"
          <<" --image "+vm.vmImage
          <<" --nic net-id=c94feaf3-c08c-4ee5-8de3-ba609ac85323"
          <<" --security-group default"
          <<" --key-name "+vm.userName
          <<"key "<<vm.vmName;
    fout.close();
    QString command;
    command.append("sh ").append(shPath).append(" >> ").append(resPath);
    int res = system(command.toStdString().c_str());
    fout.remove();
    QFile fin(resPath);
    if(fin.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        result= fin.readAll();
        fin.close();
        fin.remove();
    }
    if(res!=0)
    {
        return false;
    }
    usersQuota.saveQuota(curQuota);

    return true;
}
void Create::run()
{
   if(m_passage.isEmpty())
   {
       return;
   }
   VM vm;
   if(!parsePassage(m_passage,vm))
   {
       return;
   }
   QByteArray result;
   bool res = createVm(vm,result);
   emit(replyCreateResult(m_pSocket,vm,res,result));

}
